<template>
  <div class="format-tool">
    <h2>格式化与压缩工具</h2>
    <div class="input-group">
      <label for="formatType">选择类型：</label>
      <select id="formatType" v-model="formatType">
        <option value="json">JSON</option>
        <option value="sql">SQL</option>
      </select>
    </div>
    <div class="input-group">
      <label for="inputText">输入文本：</label>
      <textarea id="inputText" v-model="inputText" rows="8" placeholder="请输入需要格式化或压缩的文本"></textarea>
    </div>
    <div class="btn-group">
      <button @click="formatText">格式化</button>
      <button @click="compressText">压缩</button>
    </div>
    <div class="result" v-if="result">
      <h3>结果：</h3>
      <textarea v-model="result" rows="8" readonly></textarea>
    </div>
    <p v-if="error" class="error">{{ error }}</p>
  </div>
</template>

<script>
import { format } from 'sql-formatter';

export default {
  name: "FormatTool",
  data() {
    return {
      formatType: "json",
      inputText: "",
      result: "",
      error: ""
    };
  },
  methods: {
    formatText() {
      this.error = "";
      try {
        if (this.formatType === "json") {
          const obj = JSON.parse(this.inputText);
          this.result = JSON.stringify(obj, null, 4);
        } else if (this.formatType === "sql") {
          this.result = format(this.inputText);
        }
      } catch (e) {
        this.error = "格式化错误：" + e.message;
      }
    },
    compressText() {
      this.error = "";
      try {
        if (this.formatType === "json") {
          const obj = JSON.parse(this.inputText);
          this.result = JSON.stringify(obj);
        } else if (this.formatType === "sql") {
          // 简单压缩 SQL：去除换行和多余空白字符
          this.result = this.inputText.replace(/\s+/g, ' ').trim();
        }
      } catch (e) {
        this.error = "压缩错误：" + e.message;
      }
    }
  }
};
</script>

<style scoped>
.format-tool {
  max-width: 600px;
  margin: 20px auto;
  padding: 10px;
}
.input-group {
  margin: 10px 0;
}
.input-group label {
  display: block;
  margin-bottom: 5px;
}
.input-group textarea,
.input-group select {
  width: 100%;
  padding: 8px;
  box-sizing: border-box;
}
.btn-group {
  margin-top: 10px;
}
.btn-group button {
  margin-right: 10px;
  padding: 8px 16px;
  background-color: #9b59b6;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
.btn-group button:hover {
  background-color: #8e44ad;
}
.result {
  margin-top: 20px;
}
.result textarea {
  width: 100%;
  padding: 8px;
  box-sizing: border-box;
}
.error {
  color: red;
  margin-top: 10px;
}
</style> 